package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.dto.FriendApplyDto;
import org.aeon.entity.dto.UserDto;
import org.aeon.message.request.FriendApplyListRequestMessage;
import org.aeon.message.response.FriendApplyListResponseMessage;
import org.aeon.service.factory.FriendApplyServiceFactory;
import org.aeon.service.factory.UserServiceFactory;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: MissingAeon
 * @date: 2024/3/6 10:51
 * @description: 好友申请列表请求处理程序
 */
@Slf4j
@ChannelHandler.Sharable
public class FriendApplyListRequestHandler extends SimpleChannelInboundHandler<FriendApplyListRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FriendApplyListRequestMessage msg) throws Exception {
        final FriendApplyListResponseMessage resMsg = new FriendApplyListResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final Long userId = msg.getUserId();
        final List<FriendApplyDto> friendApplies = FriendApplyServiceFactory.getService().getMessages(userId);

        final Map<Long, UserDto> users = UserServiceFactory.getService()
                .getBatchUserInfo(friendApplies.stream().map(FriendApplyDto::getUserId).distinct().toList())
                .stream()
                .collect(Collectors.toMap(UserDto::getId, userDto -> userDto, (o, n) -> o, HashMap::new));

        LinkedHashMap<FriendApplyDto, UserDto> combinedMap = friendApplies.stream()
                .collect(Collectors.toMap(f -> f, f -> users.get(f.getUserId()), (o, n) -> o, LinkedHashMap::new));

        resMsg.setMessage(combinedMap);
        resMsg.setResponse(true, combinedMap.size() + "条信息");
        ctx.writeAndFlush(resMsg);
    }
}
